package com.meisupic.copyright.support;

import com.alibaba.fastjson.JSON;
import com.meisupic.copyright.util.StringUtil;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * @author lanjian
 * @version V1.0
 * @Description: TODO
 * @date 2018/3/3 9:10
 */
public class HttpClient implements Serializable {

  private static RequestConfig requestConfig;

  static {
    requestConfig = RequestConfig.custom().setSocketTimeout(300000).setConnectTimeout(300000).build();
  }

  public static Response get(String url, Map<String, String> params) {
    Response response = new Response();

    StringBuffer param = new StringBuffer();
    if(!StringUtil.isEmpty(params)){
      int i = 0;
      for (String key : params.keySet()) {
        if (i == 0) {
          param.append("?");
        } else {
          param.append("&");
        }
        param.append(key).append("=").append(params.get(key));
        i++;
      }
    }
    url = url + param.toString();
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(url);
    httpGet.setConfig(requestConfig);
    CloseableHttpResponse closeableHttpResponse = null;
    try {
      closeableHttpResponse = httpClient.execute(httpGet);
      int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
      response.setStatusCode(statusCode);
      HttpEntity entity = closeableHttpResponse.getEntity();
      if (entity != null) {
        String content = EntityUtils.toString(entity, "UTF-8");
        response.setContent(content);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if(closeableHttpResponse!=null){

        try {
          closeableHttpResponse.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      httpGet.releaseConnection();
      try {
        httpClient.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return response;
  }

  public static Response post(String url, Map<String, String> params) {
    List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
    for (Map.Entry<String, String> entry : params.entrySet()) {
      NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
      pairList.add(pair);
    }
    UrlEncodedFormEntity requestentity = new UrlEncodedFormEntity(pairList,
        Charset.forName("UTF-8"));
    return execute(url, requestentity);
  }

  public static Response post(String url, String json,String charset) {
    StringEntity stringEntity;
    if(StringUtil.isEmpty(charset)){
      try {
        stringEntity = new StringEntity(json);
      } catch (UnsupportedEncodingException e) {
        stringEntity = new StringEntity(json,"UTF-8");
      }
    }else{
      stringEntity = new StringEntity(json, charset);// 解决中文乱码问题
    }
    stringEntity.setContentEncoding(charset);
    stringEntity.setContentType("application/json");
    return execute(url, stringEntity);
  }

  private static Response execute(String url, HttpEntity httpEntity) {
    Response response = new Response();
    HttpPost httpPost = new HttpPost(url);
    httpPost.setConfig(requestConfig);
    CloseableHttpClient httpClient = HttpClients.createDefault();
    httpPost.setEntity(httpEntity);
    CloseableHttpResponse closeableHttpResponse = null;
    try {
      closeableHttpResponse = httpClient.execute(httpPost);
      response.setStatusCode(closeableHttpResponse.getStatusLine().getStatusCode());
      HttpEntity entity = closeableHttpResponse.getEntity();
      if (entity != null) {
        String content = EntityUtils.toString(entity, "UTF-8");
        response.setContent(content);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (closeableHttpResponse != null) {
        try {
          closeableHttpResponse.close();
          httpPost.releaseConnection();
          httpClient.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }

    }
    return response;
  }

  public static void main(String[] args) throws Exception {
    Map<String,String> params = new HashedMap();

    List<String> lines = FileUtils.readLines(new File("/Users/lanjian/Downloads/params"));
    params.put("json",lines.get(0));
    params.put("proxySign",lines.get(1));
    params.put("applyerSign",lines.get(2));
    params.put("eCertId","BC5B0977126B4F649252816EB011BA2A");
    Response response = HttpClient.post("http://203.207.196.204:8080/DWCRServer/textregisterplugin/textregisterforesign.do",params);
    System.out.println(JSON.toJSONString(response));
  }
}
